package com.hqbzl.chat.handler;

import com.hqbzl.chat.constant.Constants;
import com.hqbzl.chat.message.RpcRequestMessage;
import com.hqbzl.chat.message.RpcResponseMessage;
import com.hqbzl.chat.service.UserService;
import com.hqbzl.chat.utils.Helper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

@ChannelHandler.Sharable
@Slf4j
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage rpc) throws Exception {
        final int sequenceId = rpc.getSequenceId();
        final RpcResponseMessage build = RpcResponseMessage.builder().build();
        build.setSequenceId(sequenceId);
        build.setReturnType(rpc.getReturnType());
        try {
            final Class<?> clazz = Class.forName(rpc.getInterfaceName());
            final Class implService = Helper.getImplSerice(clazz);
            // 从本地找实现类
            final Object object = implService.getDeclaredConstructor().newInstance();
            final Method method = implService.getMethod(rpc.getMethodName(), rpc.getParameterTypes());
            final Object invoke = method.invoke(object, rpc.getParameterValus());
            build.setObject(invoke);
        } catch (Exception e) {
            build.setException(new Exception("rpcException:" + e.getCause().getMessage()));
            e.printStackTrace();
        }
        ctx.writeAndFlush(build);
    }
}
